package com.bestcem.xm.component.mqmetrics.aspect;

import com.bestcem.xm.component.mqmetrics.service.CustomMqMetricService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

@Slf4j
@Aspect
public class MqMetricsAspect {
    @Autowired
    private CustomMqMetricService customMqMetricService;

    //TODO 路径需要看下对不对
    @Pointcut("execution(* com.bestcem.xm.*.mq.receiver.biz.ReceiverService.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法参数
        Object[] args = joinPoint.getArgs();
        MessageHeaders header = ((GenericMessage<?>) args[0]).getHeaders();
        Object offsetobj = header.get("kafka_offset");
        String topic;
        Integer offset = null;
        if (!ObjectUtils.isEmpty(offsetobj)) {
            offset = Integer.valueOf(offsetobj.toString());
            topic = String.valueOf(header.get("kafka_receivedTopic"));
        } else {
            topic = String.valueOf(header.get("amqp_receivedExchange"));
        }
        Object result;
        log.info("start execute:{}", method.getName());
        try {
            result = joinPoint.proceed();
        } catch (Exception e) {
            log.error("MetricsAspect around exception", e);
            customMqMetricService.metricError(topic, offset);
            throw e;
        }
        customMqMetricService.metricSuccess(topic, offset);
        long cost = System.currentTimeMillis() - beginTime;
        log.info("MetricsAspect cost:{} millis,end execute:{}", cost, method.getName());
        return result;
    }

}